package com.tanhua.server.server;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SmallVideosService {
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private FastFileStorageClient client;//核心对象
    // 1、自动访问tracker服务器，获取本次存储的服务器地址
    //     *      2、将文件上传到存储服务器上
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @DubboReference
    private VideoApi videoApi;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MqMessageService mqMessageService;
    //发布视频
    public void save(MultipartFile videoFile, MultipartFile videoThumbnail) throws Exception {
        //封面存在oss
        String url = ossTemplate.uploadFile(videoThumbnail.getInputStream(), videoFile.getOriginalFilename());
        //视频存在fastdfs
        InputStream is = videoFile.getInputStream();
        long size = videoFile.getSize();  //获取文件大小
        String filename = videoFile.getOriginalFilename();
        int i = filename.lastIndexOf(".");   //截取文件的后缀，，定位到
       filename= filename.substring(i + 1);
        StorePath storePath = client.uploadFile(is, size, filename, null);//输入流，大小，后缀，元数据
        String videoUrl = fdfsWebServer.getWebServerUrl()+storePath.getFullPath(); //拼接文件访问路径
        //构建vo对象
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(url);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我");
        //调api保存
         videoApi.save(video);
    }
   //查询视频列表
    public PageResult slectList(Integer page, Integer pageSize) {
        //1.从redis中查询推荐的视频，得到的value里是视频的id，逗号分隔
        String key = Constants.VIDEOS_RECOMMEND+UserHolder.getUserId();
        String value = redisTemplate.opsForValue().get(key);
        //2.判断是否存在List
        List<Video> videos = new ArrayList<>();
        //2.1存在，根据视频id集合查询视频
        if(StringUtils.isNotEmpty(value)){
            String[] ids = value.split(",");
            videos = videoApi.selectVideo(ids,page,pageSize);
        }else {
            //2.2不存在，查询所有视频
           videos = videoApi.selectAll(page,pageSize);
        }
        if(CollUtil.isEmpty(videos)){
            return new PageResult();
        }
        //提取所有视频发布者的id，并获取详细信息
        List<Long> ids = CollUtil.getFieldValues(videos, "userId", Long.class);
        Map<Long, UserInfo> infos = userInfoApi.findIds(ids);
        //将一个video转化videovo对象
        ArrayList<VideoVo> videoVos = new ArrayList<>();
        for (Video video : videos) {
            Long id = video.getUserId();
            UserInfo userInfo = infos.get(id);
            VideoVo vo = VideoVo.init(userInfo, video);
            videoVos.add(vo);
        }
        //返回
        return new PageResult(page,pageSize,0l,videoVos);
    }
  //小视频点赞
    public void like(String videoId) {
    //完成点赞的业务了的逻辑
        Long userId = UserHolder.getUserId();

    //完成点赞发送日志消息
     mqMessageService.sendLogMessage(userId,"0302","log.video",videoId);
    }
}
